// 视频上传处理
document.addEventListener('DOMContentLoaded', () => {
    console.log('=========== 上传页面初始化 ===========');
    const uploadForm = document.getElementById('uploadForm');
    const uploadBtn = document.getElementById('uploadBtn');
    const progressBar = document.getElementById('uploadProgress');
    const statusText = document.getElementById('uploadStatus');
    const videoInput = document.getElementById('video');
    const thumbnailInput = document.getElementById('thumbnail');
    const videoFileName = document.getElementById('videoFileName');
    const thumbnailFileName = document.getElementById('thumbnailFileName');

    // 检查用户是否已登录
    const token = localStorage.getItem('token');
    let user;
    
    try {
        user = JSON.parse(localStorage.getItem('user') || '{}');
    } catch (e) {
        user = {};
    }
    
    console.log('当前token:', token);
    console.log('当前用户信息:', user);
    
    if (!token) {
        statusText.textContent = '请先登录后再上传视频';
        uploadBtn.disabled = true;
        return;
    }

    // 显示选择的视频文件名
    videoInput.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
            console.log('选择的视频文件:', file.name, '大小:', file.size, '类型:', file.type);
            videoFileName.textContent = file.name;
            videoInput.classList.add('has-file');
            
            const maxSize = 500 * 1024 * 1024; // 500MB
            if (file.size > maxSize) {
                console.log('文件大小超过限制:', file.size);
                statusText.textContent = '文件大小超过500MB限制';
                videoInput.value = '';
                videoFileName.textContent = '未选择文件';
                videoInput.classList.remove('has-file');
                return;
            }
            
            // 检查文件类型
            const allowedTypes = ['video/mp4', 'video/webm', 'video/quicktime'];
            if (!allowedTypes.includes(file.type)) {
                console.log('不支持的文件类型:', file.type);
                statusText.textContent = '不支持的文件类型';
                videoInput.value = '';
                videoFileName.textContent = '未选择文件';
                videoInput.classList.remove('has-file');
                return;
            }
            
            console.log('文件验证通过');
            statusText.textContent = '文件已选择，可以开始上传';
        } else {
            videoFileName.textContent = '未选择文件';
            videoInput.classList.remove('has-file');
        }
    });

    // 显示选择的缩略图文件名
    thumbnailInput.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
            console.log('选择的缩略图文件:', file.name, '大小:', file.size, '类型:', file.type);
            thumbnailFileName.textContent = file.name;
            thumbnailInput.classList.add('has-file');
            
            // 检查文件类型
            if (!file.type.startsWith('image/')) {
                console.log('不支持的缩略图类型:', file.type);
                statusText.textContent = '缩略图必须是图片格式';
                thumbnailInput.value = '';
                thumbnailFileName.textContent = '未选择文件';
                thumbnailInput.classList.remove('has-file');
                return;
            }
        } else {
            thumbnailFileName.textContent = '未选择文件';
            thumbnailInput.classList.remove('has-file');
        }
    });

    uploadForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        console.log('=========== 表单提交开始 ===========');
        
        const formData = new FormData(uploadForm);
        const title = formData.get('title');
        const description = formData.get('description');
        const videoFile = formData.get('video');
        const thumbnailFile = formData.get('thumbnail');
        
        console.log('表单数据:', {
            title: title,
            description: description ? description.substring(0, 30) + '...' : '',
            hasVideo: !!videoFile,
            videoFileName: videoFile ? videoFile.name : null,
            hasThumbnail: !!thumbnailFile,
            thumbnailFileName: thumbnailFile ? thumbnailFile.name : null
        });

        // 确保必填字段已填写
        if (!title || !description || !videoFile) {
            console.error('表单验证失败：缺少必填字段');
            statusText.textContent = '请填写所有必填字段并选择视频文件';
            return;
        }

        uploadBtn.disabled = true;
        statusText.textContent = '正在上传...';
        progressBar.style.width = '0%';
        
        // 模拟上传进度
        let progress = 0;
        const progressInterval = setInterval(() => {
            progress += 10;
            progressBar.style.width = `${Math.min(progress, 90)}%`;
            if (progress >= 90) clearInterval(progressInterval);
        }, 300);

        try {
            // 使用真实API上传视频
            console.log('开始发送上传请求到服务器');
            const response = await fetch('/api/videos/upload', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`
                },
                body: formData
            });

            console.log('服务器响应状态:', response.status);
            const responseData = await response.json();
            console.log('服务器响应数据:', responseData);

            if (!response.ok) {
                throw new Error(responseData.error || '上传失败');
            }
            
            // 完成进度条
            clearInterval(progressInterval);
            progressBar.style.width = '100%';
            
            statusText.textContent = '上传成功！';
            
            // 清空表单
            uploadForm.reset();
            videoFileName.textContent = '未选择文件';
            thumbnailFileName.textContent = '未选择文件';
            videoInput.classList.remove('has-file');
            thumbnailInput.classList.remove('has-file');
            
            console.log('上传完成，3秒后跳转到个人中心');
            // 3秒后跳转到个人中心
            setTimeout(() => {
                window.location.href = '/profile';
            }, 3000);
        } catch (error) {
            console.error('上传过程中出错:', error);
            clearInterval(progressInterval);
            statusText.textContent = error.message || '上传过程中出错，请重试';
            uploadBtn.disabled = false;
        }
    });
    
    // 获取文件扩展名
    function getFileExtension(filename) {
        return filename.substring(filename.lastIndexOf('.'));
    }
}); 